package cn.wch.ch934xlib.chip;

import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Arrays;

import cn.wch.ch934xlib.utils.LogUtil;


public class ChipInformationUtil {

    public static ChipEntity getChipInformation(@NonNull UsbManager usbManager, @NonNull UsbDevice usbDevice, @NonNull ChipType chipType){
        if(chipType==ChipType.CH934X){
            ChipEntity channelOnCH934X = getChannelOnCH934X(usbDevice);
            if(channelOnCH934X!=null){
                LogUtil.d("get chip info: "+channelOnCH934X.toString());
            }
            return channelOnCH934X;

        }
        return null;
    }

    private static ChipEntity getChannelOnCH934X(@NonNull UsbDevice usbDevice){
        ChipEntity chipEntity=new ChipEntity();

        int interfaceCount = usbDevice.getInterfaceCount();
        for (int i = 0; i < interfaceCount; i++) {
            UsbInterface anInterface = usbDevice.getInterface(i);
            int endpointCount = anInterface.getEndpointCount();
            for (int i1 = 0; i1 < endpointCount; i1++) {
                UsbEndpoint endpoint = anInterface.getEndpoint(i1);
                //区分端点
                if(endpoint.getEndpointNumber()==1){
                    if(endpoint.getDirection()== UsbConstants.USB_DIR_IN){
                        chipEntity.setCtrlEpIn(endpoint);
                    }else if(endpoint.getDirection()== UsbConstants.USB_DIR_OUT){
                        chipEntity.setCtrlEpOut(endpoint);
                    }

                }else if(endpoint.getEndpointNumber()==2){
                    if(endpoint.getDirection()== UsbConstants.USB_DIR_IN){
                        chipEntity.setBulkEpIn(endpoint);
                    }else if(endpoint.getDirection()== UsbConstants.USB_DIR_OUT){
                        chipEntity.setBulkEpOut(endpoint);
                    }

                }
            }
            if(!chipEntity.isValid()){
                continue;
            }else {
                chipEntity.setChipType(ChipType.CH934X);
                chipEntity.setUsbInterface(anInterface);
                chipEntity.setUsbDevice(usbDevice);
                return chipEntity;
            }
        }
        return null;
    }

}
